package com.boco.fznq.network;

import android.util.Log;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 *
 * Created by jiangcheng on 2017/8/10.
 */

public class OkHttpClientFactory {


    private static final int DEFAULT_CONNECT_TIMEOUT = 10;

    private static final int DEFAULT_READ_TIMEOUT = 15;

    private static final int DEFAULT_WRITE_TIMEOUT = 15;

    /**
     * OKHttpClient实例
     */
    private OkHttpClient mOkHttpClient;

    /**
     * 初始化
     */
    private void init() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(
                new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {
                        Log.d("okhttp", message);
                    }
                });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS)
                // 统一添加User-Agent的Header,
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Request.Builder newBuilder = request.newBuilder();
                        newBuilder.addHeader("User-Agent", NetworkUtils.getDefaultUserAgent());
                        return chain.proceed(newBuilder.build());
                    }
                })
                .retryOnConnectionFailure(true)
                .addInterceptor(loggingInterceptor)
                .build();
    }

    /**
     * 默认的OkHttp
     *
     * @return
     */
    public OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }

    public static OkHttpClientFactory create() {
        OkHttpClientFactory okHttpClientFactory = new OkHttpClientFactory();
        okHttpClientFactory.init();
        return okHttpClientFactory;
    }

}
